package com.reddys.rad.inventory.controller;



/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import com.reddys.rad.inventory.db.Product;
import com.reddys.rad.inventory.db.ProductCategory;
import com.reddys.rad.inventory.db.Vendor;
import com.reddys.rad.inventory.service.SalesService;
import com.reddys.rad.inventory.utils.EntityManagerImpl;
import com.reddys.rad.inventory.utils.Utilities;
import java.math.BigInteger;


import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Logger;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javafx.util.Callback;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;


/**
 * FXML Controller class
 *
 * @author Arun
 */
public class ProductmasterController implements Initializable {

    Logger log  = Utilities.getLogger("ProductmasterController");
    @FXML
    private TextField productID;
    @FXML
    private TextField productName;
    @FXML
    private TextField itemCode;
    @FXML
    private TextField batchCode;
    @FXML
    private TextField uom;
    @FXML
    private TextField reorderValue;
    @FXML
    private TableView productTable;
    @FXML
    private TableColumn tableProductID;
    @FXML
    private TableColumn tableProductName;
    @FXML
    private TableColumn tableItemCode;
    @FXML
    private TableColumn tableBatchCode;
    @FXML
    private TableColumn tableProductUOM;
    @FXML
    private TableColumn tableReorderValue;
    @FXML
    private ComboBox productCategory;
    @FXML
    private TableColumn tableproductCategory;
    
    

    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        try{
      populateProducttable();
      ObservableList list=FXCollections.observableArrayList();
      list.addAll(getProductCategory());
        System.out.println("list"+list.toString());
      productCategory.setItems(list);
           productTable.setOnMouseClicked(new EventHandler<MouseEvent>() {

            @Override
            public void handle(MouseEvent t) {
                ObservableList product=(ObservableList)productTable.getSelectionModel().getSelectedItem();
                productID.setText((String)product.get(0));
                productName.setText((String)product.get(1));
                itemCode.setText((String)product.get(2));
                batchCode.setText((String)product.get(3));
                uom.setText((String)product.get(4));
                reorderValue.setText((String)product.get(5));
                productCategory.setValue((String)product.get(6));
            }
        });
        }catch(Exception e){
            e.printStackTrace();
            log.info(e.getMessage());
           
        }
    }

    @FXML
    public void save(ActionEvent event) {
        try{
            if(validateSave()){
        System.out.println("product" + productID.getText());
        Product product = new Product();
        Boolean flag=false;
        if(productID.getText()!=null && productID.getText().length()>0){
            product.setProductId(productID.getText());
            flag=true;
        }
        System.out.println("ptidfgjfdg-----------=============>"+productID.getText().length());
//        System.out.println("ptidfgjfdg"+product.getProductId().length());
        //product.setProductId(productID.getText());
        product.setProductDescription(productName.getText());
        product.setItemCode(itemCode.getText());
        product.setBatchCode(batchCode.getText());
        product.setStandardUom(uom.getText());
        product.setReorderLevel(new BigInteger(reorderValue.getText()));
        ProductCategory category = SalesService.getProductCategoryByDesc(productCategory.getSelectionModel().getSelectedItem().toString());
        product.setProductCategoryId(category.getProductCategoryId());
       /*EntityManager manager=getDBConnetion();
        manager.getTransaction().begin();
        manager.persist(product);
        manager.getTransaction().commit();*/
        System.out.println("flag----------------->"+flag);
         Product product1;
        if(flag){
            product1=(Product) EntityManagerImpl.merge(product);  
        }else {
            product1=(Product) EntityManagerImpl.persist(product);   
        }
       
        productID.setText(product1.getProductId());
         populateProducttable();
         Utilities.createDialog("Transaction Completed Successfully");
            }
                }catch(Exception e){
            log.info(e.getMessage());
        }
    }

        @FXML
    public void clear(ActionEvent event) {
        productID.setText(null);
        productName.setText(null);
        itemCode.setText(null);
        batchCode.setText(null);
        uom.setText(null);
        reorderValue.setText(null);
        productCategory.setValue(null);
    }
        
    public static EntityManager getDBConnetion() {
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("purchasemodule");
        EntityManager manager = factory.createEntityManager();
        return manager;

    }
    
    public  void populateProducttable(){
        EntityManager manager=EntityManagerImpl.getEntityManager();
        Query query=manager.createNamedQuery("Product.findAll");
          List<Product> list= (List<Product>) query.getResultList();
           
           ObservableList list2= FXCollections.observableArrayList();
         for(Product l:list){
             ObservableList list1= FXCollections.observableArrayList();
             list1.add(l.getProductId());
             list1.add(l.getProductDescription());
             list1.add(l.getItemCode());
             list1.add(l.getBatchCode());
             list1.add(l.getStandardUom());
             list1.add(l.getReorderLevel()!=null?l.getReorderLevel().toString():"");
             list1.add(l.getProductCategoryId());
             System.out.println("----------"+l.getProductCategoryId());
            list2.add(list1);
         } 
         
       
         productTable.getItems().clear();;
        productTable.setItems(list2);
        System.out.println("heelooooooooooo"+list2.size());
        tableProductID.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
              return new SimpleStringProperty(cdf.getValue().get(0)!=null?cdf.getValue().get(0).toString():"");
            }
           

           
        });
        
        tableProductName.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
              return new SimpleStringProperty( cdf.getValue().get(1)!=null?cdf.getValue().get(1).toString():"");
            }
           

           
        });
        
        tableItemCode.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
              return new SimpleStringProperty( cdf.getValue().get(2)!=null?cdf.getValue().get(2).toString():"");
            }
           

           
        });
        
        tableBatchCode.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
             return new SimpleStringProperty( cdf.getValue().get(3)!=null?cdf.getValue().get(3).toString():"");
            }
            
           

           
        });
        
        tableProductUOM.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
              return new SimpleStringProperty( cdf.getValue().get(4)!=null?cdf.getValue().get(4).toString():"");
            }
           

           
        });
        
        tableReorderValue.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
              return new SimpleStringProperty( cdf.getValue().get(5)!=null?cdf.getValue().get(5).toString():"");
            }
           

           
        });
        tableproductCategory.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
              return new SimpleStringProperty( cdf.getValue().get(6)!=null?cdf.getValue().get(6).toString():"");
            }
           

           
        });
        //productTable.getItems().add(uom);
       
        
    }
    
    
    public ObservableList getProductCategory(){
        
        EntityManager manger=EntityManagerImpl.getEntityManager();
        Query query=manger.createNamedQuery("ProductCategory.findAll");
        ObservableList list =FXCollections.observableArrayList();
        System.out.println(""+query.getResultList().size());
        for(int i=0;i<query.getResultList().size();i++){
            ProductCategory category=(ProductCategory)query.getResultList().get(i);
            list.add(category.getProductCategoryDescription());
        }
        System.out.println("Product Catge"+list.toString());
        return list;
        
    }

    private boolean validateSave() {
        
        if(Utilities.isNull(productName.getText())){
            Utilities.createDialog("Please enter product name"+productName.getText());
            return false;
        }
        if(Utilities.isNull(uom.getText())){
            Utilities.createDialog("Please enter UOM");
            return false;  
        }
        if(Utilities.isNull(reorderValue.getText())){
            Utilities.createDialog("Please enter re-order value");
            return false;  
        }
        String category = (String) productCategory.getSelectionModel().getSelectedItem();
        if(Utilities.isNull(category)){
            Utilities.createDialog("Please select product category");
            return false;  
        }
     return true;
    }
    
}
